<template>
  <t-form
    ref="form"
    :class="['item-container', `register-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <t-form-item name="username" label="用户名" required>
      <t-input v-model="formData.username" size="large" placeholder="请输入您的用户名">
        <template #prefix-icon>
          <user-circle-icon />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item name="password" label="密码" required>
      <t-input
        v-model="formData.password"
        size="large"
        :type="showPsw ? 'text' : 'password'"
        clearable
        placeholder="请输入登录密码"
      >
        <template #prefix-icon>
          <lock-on-icon />
        </template>
        <template #suffix-icon>
          <browse-icon v-if="showPsw" key="browse" @click="togglePasswordVisibility" />
          <browse-off-icon v-else key="browse-off" @click="togglePasswordVisibility" />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item name="confirm_password" label="确认密码" required>
      <t-input
        v-model="formData.confirm_password"
        size="large"
        :type="showPsw ? 'text' : 'password'"
        clearable
        placeholder="请再次输入登录密码"
      >
        <template #prefix-icon>
          <lock-on-icon />
        </template>
        <template #suffix-icon>
          <browse-icon v-if="showPsw" key="browse" @click="togglePasswordVisibility" />
          <browse-off-icon v-else key="browse-off" @click="togglePasswordVisibility" />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item name="email" label="邮箱" required>
      <t-input v-model="formData.email" type="email" size="large" placeholder="请输入您的邮箱">
        <template #prefix-icon>
          <mail-icon />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item name="phone" label="手机号" required>
      <t-input v-model="formData.phone" :maxlength="11" size="large" placeholder="请输入您的手机号">
        <template #prefix-icon>
          <user-icon />
        </template>
      </t-input>
    </t-form-item>
    <t-form-item class="verification-code" name="verify_code" label="验证码" required>
      <t-input v-model="formData.verify_code" size="large" placeholder="请输入验证码" />
      <t-button variant="outline" :disabled="countDown > 0" @click="handleSendVerifyCode">
        {{ countDown === 0 ? '发送验证码' : `${countDown}秒后可重发` }}
      </t-button>
    </t-form-item>
    <t-form-item class="check-container" name="checked" label=" " required>
      <t-checkbox v-model="formData.checked">我已阅读并同意 </t-checkbox>
      <span @click="openAgreement">TDesign服务协议</span> 和 <span @click="openPrivacy">TDesign 隐私声明</span>
    </t-form-item>
    <t-form-item>
      <t-button block size="large" type="submit">注册</t-button>
    </t-form-item>
  </t-form>
</template>

<script lang="ts">
import Vue from 'vue';
import { UserIcon, MailIcon, BrowseIcon, BrowseOffIcon, LockOnIcon, UserCircleIcon } from 'tdesign-icons-vue';

const INITIAL_DATA = {
  username: '',
  password: '',
  email: '',
  confirm_password: '',
  phone: '',
  verify_code: '',
  checked: false,
};

const FORM_RULES = {
  username: [{ required: true, message: '用户名必填', type: 'error' }],
  phone: [{ required: true, pattern: /^1\d{10}$/, message: '请输入有效的手机号', type: 'error' }],
  email: [{ required: true, type: 'email', message: '请输入有效的邮箱' }],
  password: [{ required: true, min: 8, message: '密码太简单了吧', type: 'error' }],
  confirm_password: [
    { required: true, message: '请确认密码', type: 'error' }
  ],
  verify_code: [{ required: true, message: '请输入验证码', type: 'error' }],
};

export default Vue.extend({
  name: 'Register',
  components: {
    UserIcon,
    MailIcon,
    BrowseIcon,
    BrowseOffIcon,
    LockOnIcon,
    UserCircleIcon,
  },
  data() {
    return {
      FORM_RULES,
      formData: { ...INITIAL_DATA },
      showPsw: false,
      countDown: 0,
      intervalTimer: null as number | null,
      type: 'email', // 默认注册类型，可根据需求调整
    };
  },
  beforeDestroy() {
    if (this.intervalTimer) {
      clearInterval(this.intervalTimer);
    }
  },
  methods: {
    togglePasswordVisibility() {
      this.showPsw = !this.showPsw;
    },
    async onSubmit({ validateResult }: { validateResult: boolean }) {
      if (validateResult) {
        if (!this.formData.checked) {
          this.$message.error('请同意TDesign服务协议和TDesign隐私声明');
          return;
        }
        if (this.formData.password !== this.formData.confirm_password) {
          this.$message.error('两次输入的密码不一致');
          return;
        }

        try {
          const response = await this.$request.post('user/register/', { ...this.formData });
          console.log(response);

          if (response.status === 200) {
            this.$message.success(response.data.message);
            this.$router.push('/login');
          } else {
            this.$message.error(response.data.message || '注册失败，请检查输入信息');
          }
        } catch (error) {
          console.error('注册失败:', error);
          this.$message.error('注册异常');
        }
      }
    },
    async handleSendVerifyCode() {
      if (!this.formData.phone) {
        this.$message.error('请输入手机号');
        return;
      }
      try {
        const response = await this.$request.post('user/send_verify_code/', { phone: this.formData.phone });
        console.log(response);
        if (response.status === 200) {
          this.$message.success(response.data.message);
          this.startCountDown();
        } else {
          this.$message.error(response.data.error || '发送验证码失败');
        }
      } catch (error) {
        console.error('发送验证码失败:', error);
        this.$message.error('发送验证码异常');
      }
    },
    startCountDown() {
      this.countDown = 60;
      this.intervalTimer = window.setInterval(() => {
        if (this.countDown > 0) {
          this.countDown -= 1;
        } else if (this.intervalTimer) {
          clearInterval(this.intervalTimer);
          this.intervalTimer = null;
        }
      }, 1000);
    },
    openAgreement() {
      // 打开服务协议
      // 可实现弹窗或跳转到协议页面
      this.$router.push('/agreement');
    },
    openPrivacy() {
      // 打开隐私声明
      this.$router.push('/privacy');
    },
  },
});
</script>

<style scoped>
.verification-code {
  display: flex;
  align-items: center;
}
.verification-code t-input {
  flex: 1;
}
.verification-code t-button {
  margin-left: 10px;
}
.check-container {
  display: flex;
  align-items: center;
}
.check-container span {
  color: #409eff;
  cursor: pointer;
  margin-left: 5px;
  margin-right: 5px;
}
</style>